<template>
  <div class="info_main mt-5 ml-5">
    <!--    搜素框  -->
    <div class="row" >
      <div class="col-md-2">
        <!--        <el-button @click="toggleSelection()">取消选择</el-button>-->
        <el-select v-model="fiter_check" placeholder="选择积分物品类型..." @change="changecheck">
          <el-option label="生活" value="1"></el-option>
          <el-option label="文具" value="2"></el-option>
          <el-option label="运动" value="3"></el-option>
          <el-option label="阅读" value="4"></el-option>
          <el-option label="其他" value="5"></el-option>
        </el-select>
      </div>
      <div class="col-md-7">
        <el-input  type="text"
                   v-model="findCredit"
                   style="width: 500px;"
                   placeholder="请输入积分物品名称..."
                   clearable
                   @keyup.enter.native="searchByName">
        </el-input>
                <el-button type="primary" icon="el-icon-search" @click="searchByName" class="ml-3" plain>搜索</el-button>
        <el-button type="info" icon="el-icon-delete" @click="clearFindInput()" class="ml-3">重置</el-button>
      </div>
      <!--      添加按钮-->
      <div class="col-md-3" align="right">
        <el-button type="primary" @click="addOpen()" plain><i class="el-icon-plus" ></i>添加</el-button>
      </div>
    </div>
    <div class="mt-2">
      <el-button @click="toggleSelection()">取消选择</el-button>
      <el-button type="danger" @click="handleMultipleDelete">批量删除</el-button>
    </div>
    <div class="show_data mt-2">
      <el-table
          ref="multipleTable"
          v-horizontal-scroll="'always'"
          show-overflow-tooltip
          :data="showData"
          style="width: 100%"
          :cell-style="{color: '#666', fontFamily: 'Arial',fontSize:'17px'}"
          :header-cell-style="{background:'whitesmoke', fontFamily:'Helvetica',fontSize:'20px'}"
          height="700"
          @selection-change="handleSelectionChange"
          :filter-method="filterHandler"
          tooltip-effect="dark"
          :default-sort = "{prop: 'date', order: 'descending'}">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            fixed
            prop="credit_item_time"
            label="编辑时间"
            width="220">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.credit_item_time }}</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="credit_item_name"
            label="物品名"
            width="160">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="图片：" v-show="props.row.credit_item_img !='default_credit_img.jpg'">
                <img :src="'/api/storage/credit_img/'+props.row.credit_item_img"
                     style="width:30%;height:30%;object-fit:contain;border-radius: 2px"  alt="...">
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
            prop="credit_item_type"
            label="类型"
            width="130">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.credit_item_type==1" disable-transitions type="primary">
              <span class="typeClass">生活</span>
            </el-tag>
            <el-tag v-else-if="scope.row.credit_item_type==2" disable-transitions type="success">
              <span class="typeClass">文具</span>
            </el-tag>
            <el-tag v-else-if="scope.row.credit_item_type==3" disable-transitions type="danger">
              <span class="typeClass">运动</span>
            </el-tag>
            <el-tag v-else-if="scope.row.credit_item_type==4" disable-transitions type="warning">
              <span class="typeClass">阅读</span>
            </el-tag>
            <el-tag v-else-if="scope.row.credit_item_type==5" disable-transitions type="info">
              <span class="typeClass">其他</span>
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="credit_item_req_credit"
            label="要求积分"
            width="110">
        </el-table-column>
        <el-table-column
            prop="credit_item_stock"
            label="库存"
            width="110">
        </el-table-column>
        <el-table-column
            prop="credit_item_info"
            label="物品描述"
            width="240">
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="200">
          <template slot-scope="scope">
            <el-button
                size="mini"
                @click="edit(scope.$index, scope.row)">
              <span class="btnfontClass" >编辑</span>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)">
              <span class="btnfontClass" >删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--    分页-->
      <div class="pagin mt-5 mb-5">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="creditContainerPage"
            :page-size="creditContainerSize"
            layout="total,prev, pager, next"
            :total=total>
        </el-pagination>
      </div>

      <!--编辑弹窗-->
      <el-dialog
          title="编辑积分物品"
          :visible.sync="editdialogVisible"
          width="60%">

        <!--        编辑表单-->
        <el-form ref="Editform" :model="Editform" label-width="100px" :rules="rules">


          <el-form-item label="积分物品名" :label-width="formLabelWidth" prop="credit_item_name">
            <el-input
                show-word-limit
                v-model="Editform.credit_item_name"
                maxlength="100"
                :rows="2"
                type="text">
            </el-input>
          </el-form-item>


          <el-row>
            <el-col :span="7">
              <el-form-item label="类型" :label-width="formLabelWidth" prop="credit_item_type">
                <el-select v-model="Editform.credit_item_type" placeholder="选择积分物品类型...">
                  <el-option label="生活" value="1" name="生活"></el-option>
                  <el-option label="文具" value="2" name="文具"></el-option>
                  <el-option label="运动" value="3" name="运动"></el-option>
                  <el-option label="阅读" value="4" name="阅读"></el-option>
                  <el-option label="其他" value="5" name="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="要求积分" :label-width="formLabelWidth" prop="credit_item_req_credit">
                <el-input-number v-model="Editform.credit_item_req_credit"
                                 controls-position="right"
                                 :min="0" :max="5000">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="库存" :label-width="formLabelWidth" prop="credit_item_stock">
                <el-input-number v-model="Editform.credit_item_stock"
                                 controls-position="right"
                                 :min="0" :max="5000">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述" :label-width="formLabelWidth" prop="credit_item_info">
            <el-input
                show-word-limit
                type="textarea"
                maxlength="1000"
                :rows="10"
                v-model="Editform.credit_item_info"></el-input>
          </el-form-item>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="editSave('Editform')">修 改</el-button>
          <el-button @click="openCancelEdit">取 消</el-button>
        </span>
      </el-dialog>

      <!--添加弹窗-->
      <el-dialog
          title="添加积分物品"
          :visible.sync="addialogVisible"
          width="60%"
          @close="handleClose">

        <!--        编辑表单-->
        <el-form ref="Addform" :model="Addform" label-width="100px" :rules="rules" :before-close="closeDiv">

          <el-form-item label="积分物品名" :label-width="formLabelWidth" prop="credit_item_name">
            <el-input
                show-word-limit
                v-model="Addform.credit_item_name"
                maxlength="100"
                :rows="2"
                type="text">
            </el-input>
          </el-form-item>


          <el-row>
            <el-col :span="7">
              <el-form-item label="类型" :label-width="formLabelWidth" prop="credit_item_type">
                <el-select v-model="Addform.credit_item_type" placeholder="选择积分物品类型...">
                  <el-option label="生活" value="1" name="生活"></el-option>
                  <el-option label="文具" value="2" name="文具"></el-option>
                  <el-option label="运动" value="3" name="运动"></el-option>
                  <el-option label="阅读" value="4" name="阅读"></el-option>
                  <el-option label="其他" value="5" name="其他"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="要求积分" :label-width="formLabelWidth" prop="credit_item_req_credit">
                <el-input-number v-model="Addform.credit_item_req_credit"
                                 controls-position="right"
                                 :min="0" :max="5000">
                </el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="库存" :label-width="formLabelWidth" prop="credit_item_stock">
                <el-input-number v-model="Addform.credit_item_stock"
                                 controls-position="right"
                                 :min="0" :max="5000">
                </el-input-number>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述" :label-width="formLabelWidth" prop="credit_item_info">
            <el-input
                show-word-limit
                type="textarea"
                maxlength="1000"
                :rows="10"
                v-model="Addform.credit_item_info"></el-input>
          </el-form-item>

          <el-form-item label="图片：" :label-width="formLabelWidth" prop="score_img">

            <el-upload ref="upload"
                       name="upload"
                       action="#"
                       drag
                       :file-list="fileList"
                       list-type="picture"
                       :limit="1"
                       :on-exceed="handleExceed"
                       :auto-upload="false"
                       :on-remove="handleRemove"
                       :on-change="imgChange">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-form-item>




        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitAdd('Addform')">发 布</el-button>
          <el-button @click="cancel">取 消</el-button>
          <el-button @click="clearInput('Addform')">重 置</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>

<script>
import {getAllCreditInfo,updateCreditInfo,deleteCreditInfo} from '@/api/Score'
import {deleteCollegeByID} from "@/api/College";

export default {
  name: "information_main",
  data() {
    return {
      //筛选相关
      fiter_check:'',
      //搜索相关功能
      findCredit:'',
      creditContainerPage:0, // 分页的数据：当前页数
      creditContainerSize:0, // 分页的数据：每页的数量
      total:0,
      CreditData: [],
      showData:[],
      copyData:[],
      search_info:[],
      multipleSelection: [],
      //  添加弹窗相关
      addialogVisible:false,
      Addform:{
        credit_item_name:'',
        credit_item_info:'',
        credit_item_req_credit:'',
        credit_item_stock:'',
        credit_item_type:'',

      },
      //  编辑功能相关
      editdialogVisible:false,
      Editform:{
        credit_item_id:'',
        credit_item_name:'',
        credit_item_info:'',
        credit_item_req_credit:'',
        credit_item_stock:'',
        credit_item_type:'',

      },
      formLabelWidth: '100px',
      //编辑表单验证规则
      rules: {
        credit_item_name: [
          { required: true, message: '请输入积分物品名', trigger: 'blur'},
          { min:1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
        ],
        credit_item_info: [
          { required: true, message: '请输入描述', trigger: 'blur'},
          { min:1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur'}
        ],
        credit_item_type: [
          { required: true, message: '请选择类型', trigger: 'change'}
        ],
        credit_item_stock: [
          { required: true, message: '请输入库存', trigger: 'blur'},
          {type:"number", min:1,max:5000, message: '请输入正确的积分物品库存', trigger: 'blur'}
        ],
        credit_item_req_credit: [
          { required: true, message: '请输入要求积分', trigger: 'blur'},
          {type:"number", min:1,max:5000, message: '请输入正确的积分物品要求积分', trigger: 'blur'}
        ],
      },
      fileList:[],
      file:[],







    }
  },

  methods: {
    //  文件上传相关
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      fileList=[];
      fileList.length=0;
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();
    },
    //  点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file);
    },
    //限制上传数量
    handleExceed (file, fileList) {
      this.$msg.warning('只能上传一张图片！');
    },
    //限制用户上传的图片格式和大小。
    imgChange (file,fileList) {

      this.fileList = fileList;
      var img_type = file.name.substring(file.name.lastIndexOf('.') + 1)
      var imgSize = file.size;
      var img_maxsize = 1024 * 500;

      console.log(img_type=='jpg');

      if ((img_type != 'jpg') && (img_type != 'png') && (img_type != 'JPG') && (img_type != 'JPEG') && (img_type != 'jpeg')) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片只能是JPG或PNG或JPEG格式!');
        return false;
      }

      if (imgSize>img_maxsize) {
        this.fileList = [];  //将列表清空
        this.$message.warning('上传图片大小不能超过500KB!');
        return false;
      }

      return true;
      //this.$refs.uploadElement.clearValidate();

    },
    //获取全部积分物品信息
    init(){
      getAllCreditInfo({}).then(res=>{
        this.CreditData=res.data.data;
        this.copyData=res.data.data;
        this.getShowCredit();
      })
    },
    getShowCredit(){
      this.creditContainerSize=parseInt(10);
      this.showData = this.CreditData.slice((this.creditContainerPage - 1) * this.creditContainerSize, this.creditContainerPage * this.creditContainerSize);
      this.total=parseInt(this.CreditData.length);
    },
    //根据闲置物品名进行搜索
    searchByName(){

      var search=this.findCredit;
      if(search==""||search==null)
      {
        this.$msg.error('输入框不能为空！');
        this.init();
      }
      else {
        //执行本地过滤
        var search_list=this.copyData;
        this.search_info=[];  //装搜索结果的容器

        for(let i=0;i<search_list.length;i++)
        {
          if(search_list[i].credit_item_name.indexOf(search)>=0)
          {
            this.search_info.push(search_list[i]);
          }
        }
        if(this.search_info.length==0)
        {
          this.$msg.error('未找到相关结果,刷新一下~');
        }
        this.CreditData=this.search_info;
        //分页
        this.creditContainerPage=parseInt(1);
        this.getShowCredit();

        //清空搜索框
        // this.findCredit="";
      }

    },
    //  数据筛选
    changecheck(){

      var search=this.fiter_check;
      //执行本地过滤
      var search_list=this.copyData;
      this.search_info=[];  //装搜索结果的容器
      for(let i=0;i<search_list.length;i++)
      {
        if(search_list[i].credit_item_type==search)
        {
          this.search_info.push(search_list[i]);
        }
      }
      if(this.search_info.length==0)
      {
        this.$msg.error('未找到相关结果,刷新一下~');
      }
      this.CreditData=this.search_info;
      //分页
      this.creditContainerPage=parseInt(1);
      this.getShowCredit();


    },
    //page改变时的回调函数，参数为当前页码
    handleCurrentChange(val) {

      console.log(`当前页: ${val}`);
      this.creditContainerPage= parseInt(val);
      this.getShowCredit();
    },
    openCancelEdit(){
      this.editdialogVisible = false
    },
    //编辑积分物品信息  打开编辑弹窗
    edit(index, row) {

      this.editdialogVisible=true;
      // console.log(index);
      console.log(row);
      this.Editform.credit_item_name=row.credit_item_name;
      this.Editform.credit_item_stock=row.credit_item_stock;
      this.Editform.credit_item_info=row.credit_item_info;
      this.Editform.credit_item_req_credit=row.credit_item_req_credit;
      // this.Editform.credit_item_type=row.credit_item_type;
      this.Editform.credit_item_id=row.credit_item_id;

      if(row.credit_item_type==1){
        this.Editform.credit_item_type="生活";
      }else if(row.credit_item_type==2){
        this.Editform.credit_item_type="文具";
      }else if(row.credit_item_type==3){
        this.Editform.credit_item_type="运动";
      }else if(row.credit_item_type==4){
        this.Editform.credit_item_type="阅读";
      }else if(row.credit_item_type==5){
        this.Editform.credit_item_type="其他";
      }


    },
    //提交数据 修改
    editSave(formName)
    {
      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //再次确认
          this.$confirm('确认修改?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if(this.Editform.credit_item_type=="生活"){
              this.Editform.credit_item_type=1;
            }else if(this.Editform.credit_item_type=="文具"){
              this.Editform.credit_item_type=2;
            }else if(this.Editform.credit_item_type=="运动"){
              this.Editform.credit_item_type=3;
            }else if(this.Editform.credit_item_type=="阅读"){
              this.Editform.credit_item_type=4;
            }else if(this.Editform.credit_item_type=="其他"){
              this.Editform.credit_item_type=5;
            }

            this.updateSave();

          }).catch(() => {
            this.$msg.error("修改失败！");
          });

        } else {
          this.$msg.error("修改失败！");
          return false;
        }
      });
    },
    //连接后端  进行修改
    updateSave(){
      updateCreditInfo({
        EditForm: this.Editform,
        credit_item_id:this.Editform.credit_item_id,
      }).then(res=>{
        if(res.data.code===1)
        {
          this.$msg.success("修改成功！");
          //刷新表格数据
          this.init();
          //关闭弹窗
          this.editdialogVisible=false;
        }
        else
        {
          this.$msg.error("修改失败！");
        }

        if(this.Editform.credit_item_type==1){
          this.Editform.credit_item_type="生活";
        }else if(this.Editform.credit_item_type==2){
          this.Editform.credit_item_type="文具";
        }else if(this.Editform.credit_item_type==3){
          this.Editform.credit_item_type="运动";
        }else if(this.Editform.credit_item_type==4){
          this.Editform.credit_item_type="阅读";
        }else if(this.Editform.credit_item_type==5){
          this.Editform.credit_item_type="其他";
        }


      })

    },
    //删除
    handleDelete(index, row) {

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        this.deleteSave(row.credit_item_id);

      }).catch(() => {
        this.$msg.error("取消失败！");
      });

    },
    //连接后端，进行删除
    deleteSave(credit_item_id){
      deleteCreditInfo({
        credit_item_id:credit_item_id,
        token: window.sessionStorage.getItem('token')
      }).then(res=>{
        if(res.data.code==1){
          this.$msg.success("删除成功！");
          this.getShowCredit();
        }else{
          this.$msg.error("删除失败！");
        }
        this.init();
      })

    },
    //打开添加的弹窗
    addOpen(){

      this.addialogVisible=true;

    },
    submitAdd(formName){

      //验证
      this.$refs[formName].validate((valid) => {
        if (valid) {

          //再次确认
          this.$confirm('确认发布?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            this.addSave();

          }).catch(() => {
            this.$msg.error("发布失败！");
          });

        } else {
          this.$msg.error("发布失败！");
          return false;
        }
      });

    },
    //连接后端 添加积分物品信息
    async addSave(){

      let formData = new FormData();
      // alert(this.fileList.length);
      //没有上传图片
      if(this.fileList.length==0){
        formData.append('if_img',0);
      }
      //上传了图片
      else {
        formData.append('if_img',1);
        formData.append('credit_item_img', this.fileList[0].raw);
      }

      formData.append('credit_item_name',this.Addform.credit_item_name);
      formData.append('credit_item_info',this.Addform.credit_item_info);
      formData.append('credit_item_req_credit',this.Addform.credit_item_req_credit);
      formData.append('credit_item_stock',this.Addform.credit_item_stock);
      formData.append('credit_item_type',this.Addform.credit_item_type);

      // console.log(formData);

      this.$ajax({
        url: "/api/credit/addCreditInfo",
        method: "post",
        dataType:'text',
        cache:  false , //上传文件无需缓存
        processData:  false , //用于对data参数进行序列化处理 这里必须false
        contentType:  false ,  //
        data: formData
      }).then((result)=>{

        if (result.data.code == 1) {
          this.$msg.success("发布成功！");
          this.addialogVisible=false;
          this.$refs.upload.clearFiles();
          this.init();
          this.getShowCredit();
        }
        else {
          this.$msg.error('发布失败！');
        }
      });


    },
    //重置按钮
    clearInput(formName){
      this.$refs[formName].resetFields();
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    //  关闭弹窗
    cancel() {
      this.addialogVisible = false
      // 点击取消按钮的时候清除输入框中的内容 清除验证
      //  this.$nextTick获取了节点之后进行操作
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    // 右上角 × 取消按钮
    closeDiv() {

      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();

    },
    //清空搜索框
    clearFindInput(){
      this.findCredit="";
      this.init();
    },
    handleClose(){
      this.$nextTick(() => {
        // form对应你写的<el-form ref="form"></el-form>
        this.$refs["Addform"].resetFields();
      });
      this.fileList = [];  //将列表清空
      this.fileList.length = 0;
      this.$refs.upload.clearFiles();
    },
    //取消选择
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //  批量删除
    handleMultipleDelete(rows){
      if (this.multipleSelection == '') {
        this.$message.error('您未选中任何积分物品，请重新操作！！！');
        return;
      }

      let checkArr = this.multipleSelection;  // multipleSelection存储了勾选到的数据
      let credit_item_ids = [];
      checkArr.forEach(function (item) {
        credit_item_ids.push(item.credit_item_id);

      });

      //再次确认
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        deleteCreditInfo({
          credit_item_id:credit_item_ids,
        }).then(res=>{
          if(res.data.code==1){
            this.$msg.success("批量删除成功！");
          }else{
            this.$msg.error("删除失败！");
          }
          this.init();
        });

      }).catch(() => {
        this.$msg.error("取消删除！");
      });


    },
    // 筛选器
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },




  },
  created() {

    let _this=this;

    _this.creditContainerPage=parseInt(1);

    _this.init();

    _this.$refs.table.doLayout();

  },
}
</script>

<style scoped>
.btnfontClass{
  font-size: 15px;
}
.el-pagination {
  text-align: center;
}
.typeClass{
  font-size: 14px;
}

</style>
